<template>
  <div>
    <basic-modal :modalOpt="modal" :footer="undefined" :buttonText="['','完成']" @closeModal="closeModal">
      <template>
        <div style="marginBottom:20px;textAlign:center">
            请选择要关联的注册证：
            <regisLicenseSelect
                style="width:40%;"
                :value="approvalPid"
                @change="regisLicenseChange($event)"
                >
            </regisLicenseSelect>
        </div>
        <a-transfer
        :data-source="leftData"
        :target-keys="rightData"
        :show-search="true"
        :disabled="false"
        :listStyle="listStyle"
        :titles="['待完善产品','已完善产品']"
        :filter-option="(inputValue, item) => item.title.indexOf(inputValue) !== -1"
        :show-select-all="false"
        @change="onChange"
        >
            <template
                slot="children"
                slot-scope="{
                props: { direction, filteredItems, selectedKeys, disabled: listDisabled },
                on: { itemSelectAll, itemSelect },
                }"
            >
                <a-table
                :row-selection="getRowSelection({ disabled: listDisabled, selectedKeys, itemSelectAll, itemSelect })"
                :columns="direction === 'left' ? leftColumns : rightColumns"
                :data-source="filteredItems"
                size="small"
                :scroll="{y:'43vh'}"
                :loading="loading"
                :style="{ pointerEvents: listDisabled ? 'none' : null }"
                :custom-row="({ key, disabled: itemDisabled }) => ({
                    on: {
                        click: () => {
                        if (itemDisabled || listDisabled) return;
                        itemSelect(key, !selectedKeys.includes(key));
                        },
                    },
                })"
                />
            </template>
        </a-transfer>
        <a-checkbox @change="onCheckbox1">品名匹配</a-checkbox>
        <a-checkbox @change="onCheckbox2">生产厂家匹配</a-checkbox>
        
      </template>
    </basic-modal>
  </div>
</template>

<script>
import basicModal from '@/views/app/biz/common/basicModal'
import regisLicenseSelect from '@/views/app/biz/regisLicense/regisLicenseSelect'
import {
  getByAreaUse,
  getByAreaUseCount,
  saveInfos,
} from '../purchasedGoods/purchasedgoods'
import {getInfoByPid} from '@/views/app/biz/regisLicense/regisLicense'
import difference from 'lodash/difference';
export default {
  components: {
    basicModal,
    regisLicenseSelect
  },
  data() {
    return {
      loading: false,
      modal: {
        modalVisible: false,
        modalTitle: '关联注册证',
        modalWidth: '90vw',
        maxHeight:'78vh',
      },
      paginationView: {
        //分页配置
        current: 1, //当前页码 current
        pageSize: 10, //每页显示条数 pageSize
        total: 1,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['5', '10','50', '100000'],
      },
      pagination: {
        //分页配置
        current: 1, //当前页码 current
        pageSize: 1000000, //每页显示条数 pageSize
      },
      q_formDatas:{
          areaUse:null,
          productNameZh:null,
          manufacturerZh:null,
          pid:null
      },
      approvalPid:null,
      regInfo:{},
      listStyle:{height:'69vh',overflow:'scroll',width:'50%'},
      orgListdata:[],
      //左边数据
      leftData:[],
      //右边数据
      rightData: [],
      leftColumns: [
        { title: '品名', dataIndex: 'productNameZh', key: 'productNameZh', align: 'center' },
        { title: '注册证号', dataIndex: 'approvalNum', key: 'approvalNum', align: 'center' },
        { title: '规格', dataIndex: 'spec', key: 'spec', align: 'center' },
      ],
      rightColumns: [
        { title: '品名', dataIndex: 'productNameZh', key: 'productNameZh', align: 'center' },
        { title: '注册证号', dataIndex: 'approvalNum', key: 'approvalNum', align: 'center' },
        { title: '规格', dataIndex: 'spec', key: 'spec', align: 'center' },
      ],
      checked1:false,
      checked2:false,
    }
  },
  computed: {},
  mounted() {
  },
  methods: {
    // 点击了单个匹配注册证  接收产品数组
    editModal(val) {
      
    },
    // 点击了所有匹配注册证  接收产品数组
    matchAllModal(pid) {
      if (pid) {
        this.q_formDatas.pid=pid
      }else{
        this.q_formDatas.pid=null
      }
      console.log(pid);
      this.leftData=[]
      this.rightData=[]
      this.orgListdata=[]
      this.approvalPid=null
      this.getList()
      this.modal.modalVisible = true
      this.modal.modalTitle = "关联注册证"
    },
    // 关闭模态详细框
    closeModal() {
      this.modal.modalVisible = false
      // this.$emit('close')
      //关闭时刷新
      this.$emit('ok')
    },
    // 保存成功关闭模态详细框
    closeModal2() {
      this.modal.modalVisible = false
      this.$emit('ok')
    },
    async getList() {
      if(this.checked1){
        this.q_formDatas.productNameZh=this.regInfo.chanPinmc?this.regInfo.chanPinmc:'该注册证下无产品'
      }else{
        this.q_formDatas.productNameZh=null
      }
      if(this.checked2){
        this.q_formDatas.manufacturerZh=this.regInfo.shengChancsmc?this.regInfo.shengChancsmc:'该注册证下无生产企业'
      }else{
        this.q_formDatas.manufacturerZh=null
      }
      this.loading = true
      let listdata = []
      let res = ''
      res = await getByAreaUse(this.q_formDatas, this.pagination)
      this.loading = false
      console.log(this.q_formDatas)
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        const resdata = res.data
        for (let item of resdata) {
            listdata.push({
                key: item.pid,
                title: item.productNameZh,
                productNameZh: item.productNameZh,
                approvalNum: item.approvalNum,
                spec:item.spec
            })
        }
        this.leftData =listdata
        this.orgListdata=res.data
        this.paginationView.total=this.leftData.length
      } else {
        this.leftData = []
        this.orgListdata=[]
      }
    },
    async getRightList() {
      if(this.checked1){
        this.q_formDatas.productNameZh=this.regInfo.chanPinmc?this.regInfo.chanPinmc:'该注册证下无产品'
      }else{
        this.q_formDatas.productNameZh=null
      }
      if(this.checked2){
        this.q_formDatas.manufacturerZh=this.regInfo.shengChancsmc?this.regInfo.shengChancsmc:'该注册证下无生产企业'
      }else{
        this.q_formDatas.manufacturerZh=null
      }
      let res = ''
      let params={
        approvalPid:this.approvalPid,
        ...this.q_formDatas
      }
      let listdata=[]
      console.log(params);
      res = await getByAreaUse(params, this.pagination)
      if (res && res.code && res.code === 'C1' && res.data) {
        const resdata = res.data
        for (let item of resdata) {
            listdata.push(item.pid)
        }
        this.rightData=listdata
      } else {
        this.rightData=[]
      }
    },
    async getInfoByPid(val){ 
        let res=await getInfoByPid(val);
        console.log(res);
        if (res && res.code && res.code === 'C1' && res.data) {
            this.getRightList()
            this.regInfo=res.data
            if (this.checked1||this.checked2) {
                this.getList()
            }
        }
    },
    regisLicenseChange(val){
      this.approvalPid=val
      if (val) {
        this.getInfoByPid(val)
      }
    },
    onCheckbox1(e){
        console.log(e.target.checked);
        this.checked1=e.target.checked
        this.getList()
    },
    onCheckbox2(e){
        console.log(e.target.checked);
        this.checked2=e.target.checked
        this.getList()
    },
    onChange(targetKeys, direction, moveKeys) {
      if (!this.approvalPid) {
        this.$message.warning({content:'未选择要关联的注册证',duration:3})
        return
      }
      let reqArr=[]
      for (let item of moveKeys) {
        let orgItem=this.orgListdata.find(items=>{
          return items.pid==item
        })
        console.log(orgItem);
        if(orgItem){
          let reqItem={
            ...orgItem,
            approvalPid:direction == 'right'?this.approvalPid:'',
            approvalNum:direction == 'right'?this.regInfo.zhengZhaohm:''
            
          }
          console.log(reqItem);
          reqArr.push(this.saveObjInfo(reqItem))
        }
        
      }
      this.dealResult(reqArr,direction)
      
    },
        // 保存详细信息
    async saveObjInfo(val) {
      let res = await saveInfos(val)
      return res
    },
    // 保存详细信息
    dealResult(reqArr,direction) {
      return Promise.all(reqArr).then(res => {
        console.log(res)
        for (const item of res) {
          if (item && item.code && item.code === 'C1' && item.data) {
            console.log(direction);
            // if(direction=='right'){
            //   this.rightData.push(item.data.pid);
            // }else{
            //   let index=this.rightData.findIndex(key=>{
            //     return key==item.data.pid
            //   })
            //   console.log(index);
            //   this.rightData.splice(index,1);
            // }
            this.getList()
            this.getRightList()
            this.$message.success({ content: '商品:'+item.data.productNameZh+'修改成功', duration: 2 })
          } else {
            this.$message.error({ content: '商品:'+item.data.productNameZh+'修改失败，请稍后再试', duration: 2 })
          }
        }
      }).catch(err => {
        this.$message.error({ content:'请求出错:'+err, duration: 3 })
      })
    },
    getRowSelection({ disabled, selectedKeys, itemSelectAll, itemSelect }) {
      return {
        getCheckboxProps: item => ({ props: { disabled: disabled || item.disabled } }),
        onSelectAll(selected, selectedRows) {
          const treeSelectedKeys = selectedRows
            .filter(item => !item.disabled)
            .map(({ key }) => key);
          const diffKeys = selected
            ? difference(treeSelectedKeys, selectedKeys)
            : difference(selectedKeys, treeSelectedKeys);
          itemSelectAll(diffKeys, selected);
        },
        onSelect({ key }, selected) {
          itemSelect(key, selected);
        },
        selectedRowKeys: selectedKeys,
      };
    },

    // // 模态详细框提交按钮
    // onSubmit(val) {
    //   this.saveObjInfo(val)
    // },
    // // 保存详细信息
    // async saveObjInfo(val) {
    //   this.loading = true
    //   // this.$message.loading({ content: '提交中'， })
    //   let res = await saveInfos(val)
    //   this.loading = false
    //   console.log(res)
    //   if (res && res.code && res.code === 'C1' && res.data) {
    //     this.$message.success({ content: '提交成功',  duration: 2 })
    //     this.closeModal2()
    //   } else {
    //     this.$message.error({ content: '提交失败',  duration: 2 })
    //   }
    // },
  },
}
</script>

<style>
</style>